import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { FileUploader } from '_ng2-file-upload@1.2.1@ng2-file-upload';
import { UEditorComponent } from '_ngx-ueditor@1.0.7@ngx-ueditor';
import { Tour } from '../../extras/tour';
import { TournoteService } from '../../services/tour/tournote.service';

@Component({
  selector: 'app-publish-travelnote',
  templateUrl: './publish-travelnote.component.html',
  styleUrls: ['./publish-travelnote.component.css']
})
export class PublishTravelnoteComponent implements OnInit {
  [x: string]: any;

    uploader:FileUploader = new FileUploader({
      url:"/tournote/fileUpload.php",
      method:"POST",
      itemAlias:"uploadedfile"
    });

  constructor(private ts:TournoteService) { }

  ngOnInit() {
  }
//--------------------------------------------------------
  @ViewChild("file") myUpload:ElementRef;
  imgUrl:string = "../../../assets/img/addtop.png";

  clickFile(){ //相当于调用type==file的隐藏input框
    this.myUpload.nativeElement.click();
  }
  selectFile(event:any){
    let that = this;
    //文件渲染
    let reader = new FileReader();
    reader.readAsDataURL(event.target.files[0]);//获取图片地址  但在这里不可以直接拿到地址
    reader.onload = function(){
      that.imgUrl = this.result;
      //这里的onload表示成功后才执行，而result就是上面取到的图片地址。相当于onsuccess回调函数
    } 
  }

//------------------------------------------------



//-------------------------------------------------
  @ViewChild("ue") ue:UEditorComponent;
  tour:Tour = new Tour(null,"","","","","","");

  upsql(){
    console.log(this.ue.Instance.getContent());
    console.log(this.tour.title);
    console.log(this.tour.type);
    this.tour.content = this.ue.Instance.getContent();

    this.uploadImgFuntion((data)=>{
      // 2、发布内容
      this.tour.contentImg = data.imgUrl;
      this.ts.publish(this.tour).subscribe((data)=>{
         console.log(data.json());
      })
  });
} 

  uploadImgFuntion(callback:Function){
    if(this.uploader.queue.length==0){
      console.log("没有待上传的文件");
      return;
    }
    let index = this.uploader.queue.length-1;
    // 回调函数是异步处理
    this.uploader.queue[index].onSuccess = (response,status,headers)=>{
      if(status==200){
        callback(JSON.parse(response));
      }else{
        console.log("服务器不通，请稍后再试");
      }
    }

    this.uploader.queue[index].upload();
  }
  

}

